package com.itlnn.xfeng.painviw;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

import com.hanvon.penenginejni.HWPenEngine;

import java.io.InputStream;

public class PaintView extends SurfaceView implements Callback {
	//public static String otherLocation = "/sdcard/hanvon/com.hanvon.hpad.coolpaint/res/other/";
	public static String otherLocation = "/sdcard/";
	SurfaceHolder mSurfaceHolder = null;
	//画笔迹的Bitmap
	private Bitmap  mPaintSurface=null;
	private int[] mPixels;
	public Canvas mPaintCanvas = null;
	private Paint mPaint = null;
	//画笔迹的Bitmap的高度与宽度
	private int mHeight;
	private int mWidth;
	// 绘画过程中，修改的区域
	int[] rectUpdate;
	boolean mIsDown;
	long engine;
	int color=Color.YELLOW;
	public PaintView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// 实例化mSurfaceHolder
		mSurfaceHolder = this.getHolder();
		// 添加回调
		mSurfaceHolder.addCallback(this);
		this.setFocusable(true);
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {

		if (mPaintSurface == null) {
			Init(this.getWidth(), this.getHeight());
		} else {
			Update();
		}
	}

	// 全部更新
	public void Update() {
		Update(new Rect(0, 0, this.getWidth(), this.getHeight()));
	}

	// 更新区域
	public void Update(Rect rect) {
		if (rect != null && !rect.isEmpty()) {
			try {
				mPaintSurface.setPixels(mPixels, rect.top * this.getWidth()
								+ rect.left, this.getWidth(), rect.left, rect.top,
						rect.width(), rect.height());
				Canvas canvas = mSurfaceHolder.lockCanvas(rect);
				DrawLayers(canvas);
				mSurfaceHolder.unlockCanvasAndPost(canvas);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {

	}

	// 清空
	public void Clear() {
		mPaintSurface.eraseColor(Color.TRANSPARENT);
		mPaintSurface.getPixels(mPixels, 0, this.getWidth(), 0, 0,
				this.getWidth(), this.getHeight());
		this.Update();
	}

	public void ChangePenType(int penType)
	{
		HWPenEngine.setPenStyle(engine, penType);
	}




	Bitmap bristleDaBitmap=null;
	Bitmap bm1=null;
	// 初始化
	private void Init(int width, int height) {
//		this.setZOrderOnTop(true);
//		this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
		// 创建画布
		mPaintSurface = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
//		BitmapFactory.Options options = new BitmapFactory.Options() ;
//		options.inJustDecodeBounds = true ;
		mPaintSurface = zoomBitmap(getContext() , width , height , R.drawable.body_bg2) ;

//		bm1 = BitmapFactory.decodeResource(getContext().getResources() , R.drawable.koala) ;
//		mPaintSurface=bm1;
		mPixels = new int[width * height];
		mPaintSurface.getPixels(mPixels, 0, width, 0, 0, width, height);
		mPaintCanvas = new Canvas(mPaintSurface);

//		mPaintSurface=bm1;

		mPaint = new Paint();
		rectUpdate=new int[4];
		mWidth=width;
		mHeight=height;
		// 与绘画核心关联
		engine=HWPenEngine.initialize(width, height, mPixels);
		HWPenEngine.setPenStyle(engine, 14);
		HWPenEngine.setColor(engine, (byte)0, (byte)0, (byte)255, (byte)255);

		//bristleDaBitmap = BitmapFactory.decodeFile(otherLocation+"oilbrush.png");
		//bristleDaBitmap=BitmapFactory.decodeFile(otherLocation+"writtingbrush.png");
		bristleDaBitmap=BitmapFactory.decodeFile(otherLocation+"watercolour.png");
//		bristleDaBitmap = readBitMap(this.getContext(), R.raw.oilbrush);
		//bristleDaBitmap = readBitMap(this.getContext(), R.drawable.writing_brush);


		HWPenEngine.setBristlDabImage(engine, bristleDaBitmap);

		HWPenEngine.setSize(engine, 50);
		this.Update();
	}


	/**
	 * 以最省内存的方式读取本地资源的图片
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap readBitMap(Context context, int resId){
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		//获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is,null,opt);
	}

	public Bitmap zoomBitmap(Context context , int width , int height  , int resId) {
		Bitmap bitmap = readBitMap(context , resId) ;
		float bWidth = bitmap.getWidth() ;
		float bHeight = bitmap.getHeight() ;
		Matrix matrix = new Matrix() ;
		float scaleWidth = (float)width / bWidth ;
		float scaleHeight = (float)height / bHeight ;
		matrix.postScale(scaleWidth , scaleHeight) ;
		Bitmap newBitmap = Bitmap.createBitmap(bitmap , 0 , 0 , (int)bWidth , (int)bHeight , matrix , true) ;
		bitmap.recycle();
		bitmap = null ;
		return newBitmap ;

	}


	public void SetColor(byte b,byte g,byte r,byte a) {
		HWPenEngine.setColor(engine, b,g,r,a);
	}

	public void SetSize(int size) {
		HWPenEngine.setSize(engine, size);
	}

	// 绘画事件
	@TargetApi(14)
	public boolean onTouchEvent(MotionEvent e) {

		Point pf = new Point((int) e.getX(), (int) e.getY());
		float pressure = 1.0f;

		if (e.getToolType(0) == MotionEvent.TOOL_TYPE_FINGER) {
			pressure = 1.0f;
		} else if (e.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS) {
			pressure = e.getPressure();
		} else if (e.getToolType(0) == MotionEvent.TOOL_TYPE_ERASER) {
			pressure = e.getPressure();
		}

		//Android4.0调用，判断第一个触控点类型，然后获取相应压感即可
		switch (e.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (!mIsDown) {
					mIsDown = true;
					HWPenEngine.beginStroke(engine);
					HWPenEngine.strokePoint(engine, pf.x, pf.y, pressure,rectUpdate);
					Rect trect=new Rect(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
					trect.intersect(0, 0, mWidth, mHeight);
					//trect.union(touchedRect);
					Update(trect);
				}
				break;
			case MotionEvent.ACTION_MOVE:
				if (mIsDown) {
					HWPenEngine.strokePoint(engine, pf.x, pf.y, pressure,rectUpdate);
					Rect trect=new Rect(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
					trect.intersect(0, 0, mWidth, mHeight);
					//trect.union(touchedRect);
					Update(trect);
					//touchedRect.set(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
				}
				break;
			case MotionEvent.ACTION_UP:
				if (mIsDown) {
					mIsDown = false;
					HWPenEngine.endStroke(engine, rectUpdate);
					Rect trect=new Rect(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
					trect.intersect(0, 0, mWidth, mHeight);
					//trect.union(touchedRect);
					//Update(trect);
					Update();
					//touchedRect.set(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
				}
				break;
			default:
				break;
		}
		return true;
	}

	// 在Canvas上绘制所有图层
	public void DrawLayers(Canvas canvas) {
		if (canvas != null) {
			canvas.drawColor(Color.WHITE);
			//canvas.drawBitmap(mPaintSurface, matrix, paint)
			mPaint.setAlpha(255);
			canvas.drawBitmap(mPaintSurface, 0, 0, mPaint);
		}
	}

	public boolean DestroyEngine()
	{
		return HWPenEngine.destroyEngine(engine);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub

	}
}
